﻿using System;
using System.Windows;
using System.Windows.Media;
using Microsoft.Phone.Controls;
using Kiva7.Utilities;
using Kiva7.DataClasses;

namespace Kiva7.Pages
{
    public partial class FullImagePage
    {
        private const string ImageIdKey = "ImageId";

        private const string Url = "/Pages/FullImagePage.xaml";
        public readonly static Uri PageUrl = new Uri(Url, UriKind.RelativeOrAbsolute);

        public static Uri GetPageUrl(int imageId)
        {
            UrlCreator url = new UrlCreator(Url);
            url.Add(ImageIdKey, imageId);

            return url.ToUri(UriKind.RelativeOrAbsolute);
        }


        public FullImagePage()
        {
            InitializeComponent();
            CreateStandardControls();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            int imageId;
            if (int.TryParse(NavigationContext.QueryString[ImageIdKey], out imageId))
            {
                ImageSourceConverter c = new ImageSourceConverter();
                Image.Source = c.ConvertFrom(Kiva7.DataClasses.Image.CreateImageUri(imageId, ImageSize.FullSize)) as ImageSource;
            }
        }

        private double _initialScale;
        private void OnPinchDelta(object sender, PinchGestureEventArgs e)
        {
            // update the rotation and scaling
            //scale.Rotation = _initialAngle + e.TotalAngleDelta;
            scale.ScaleX = _initialScale * e.DistanceRatio;
            scale.ScaleY = scale.ScaleX;
        }

        private void OnPinchStarted(object sender, PinchStartedGestureEventArgs e)
        {
            // store the initial rotation angle and scaling
            //_initialAngle = scale.Rotation;
            _initialScale = scale.ScaleX;

            // calculate the center for the zooming
            Point firstTouch = e.GetPosition(Image, 0);
            Point secondTouch = e.GetPosition(Image, 1);

            Point center = new Point(firstTouch.X + (secondTouch.X - firstTouch.X) / 2.0,
                                        firstTouch.Y + (secondTouch.Y - firstTouch.Y) / 2.0);

            scale.CenterX = center.X;
            scale.CenterY = center.Y;
        }
    }
}